from django.shortcuts import render,HttpResponse,redirect,reverse
from user.models import User

# Create your views here.
def index_handler(request):
    context = request.context

    if 'GET' != request.method:
        return HttpResponse(status=404)

    return render(request, 'index.html', context)


def login_handler(request):
    context = request.context

    if request.method not in ['POST', 'GET']:
        return HttpResponse(status=403)

    if 'GET' == request.method:
        return render(request, 'login.html', context)

    username = request.POST.get('username')
    password = request.POST.get('password')

    try:
        user_s = User.objects.filter(username=username, password=password)

        if user_s.exists():
            context['login_user'] = user_s[0]
            request.session['login_user'] = {'id':user_s[0].id, 'username':user_s[0].username}
            request.session.set_expiry(3600)
            return redirect(reverse('user:index'))
        else:
            context['login_message'] = '用户名和密码错误'
            return render(request, 'login.html', context)
    except:
        context['login_message'] = '服务器异常'
        return render(request, 'login.html', context)
